package com.effective.java.generics;

import java.util.HashSet;
import java.util.Set;

/**
 * Class offering union capabilities for sets by means of Java Gererics
 * 
 * @author andreas.landerer
 * 
 */
public class GenericUnion {

	/**
	 * Method returning a new instance of {@link Set}
	 * 
	 * @return new instance of {@link Set}
	 */
	public static <E> Set<E> newSet() {

		return new HashSet<E>();
	}

	/**
	 * Method returning the union of two sets
	 * 
	 * @param s1
	 *            set1
	 * @param s2
	 *            set2
	 * @return union of set1 and set2 i.e. set containing all elements that are
	 *         either an element of set1 or an element of set2 or that are an
	 *         element of both sets.
	 */
	public static <E> Set<E> union(final Set<E> s1, final Set<E> s2) {

		Set<E> set = new HashSet<E>(s1);
		set.addAll(s2);
		return set;
	}

	/**
	 * Method returning the union of two sets
	 * 
	 * @param s1
	 *            set1
	 * @param s2
	 *            set2
	 * @return union of set1 and set2 i.e. set containing all elements that are
	 *         either an element of set1 or an element of set2 or that are an
	 *         element of both sets.
	 */
	public static <E> Set<E> unionWithSubTypes(final Set<? extends E> s1, final Set<? extends E> s2) {

		Set<E> set = new HashSet<E>(s1);
		set.addAll(s2);
		return set;
	}
}
